package com.burns.rbac.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.burns.rbac.commons.constants.code.HttpCodeConstants;
import com.burns.rbac.commons.constants.code.UserCodeConstants;
import com.burns.rbac.commons.exception.TokenIsNullException;
import com.burns.rbac.commons.exception.UserTokenExpiredExcption;
import com.burns.rbac.commons.exception.UserTokenVerificationException;
import com.burns.rbac.commons.utils.JWTUtils;
import com.burns.rbac.context.UserContextHolder;
import com.burns.rbac.entity.UserToken;
import com.burns.rbac.enums.UserTokenExceptionEnum;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 对token进行校验，成功放行，失败则提示
 */
@Component
public class UserTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、从请求头中获取token
        String token = request.getHeader(HttpCodeConstants.Token);


        //2、非空校验
        if (ObjectUtils.isEmpty(token)) {
            //如果token为空，则从url地址读取token信息
            token = request.getParameter(HttpCodeConstants.Token);
            if (ObjectUtils.isEmpty(token)) {
                {
                    //token为空
                    throw new TokenIsNullException(UserTokenExceptionEnum.TokenIsEmpty);
                }
            }
        }

        //3、校验token的合法性（过期超时，有误)
        try {
            JWTUtils.checkToken(token);
        } catch (TokenExpiredException e) {
            throw new UserTokenExpiredExcption(UserTokenExceptionEnum.UserTokenExpired);
        } catch (JWTVerificationException e) {
            throw new UserTokenVerificationException(UserTokenExceptionEnum.UserTokenVerificationFail);
        }

        //4、解析token，取出UserToken,放到ThreadLocal中
        UserToken userToken = JWTUtils.getUserToken(token);
        UserContextHolder.set(userToken);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //Controller调用完之后删除当前线程中的用户登录信息
        UserContextHolder.remove();
    }
}
